package com.xupx.wxutils;

import com.xupx.wxutils.cons.Constans;
import com.xupx.wxutils.pojo.WxAccessToken;
import com.xupx.wxutils.pojo.WxOpenId;
import com.xupx.wxutils.pojo.WxTicket;
import com.xupx.wxutils.pojo.WxUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 微信工具类
 * @author xupx
 */
@Component
public class WxUtils {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 推送消息接口
     * @param accessToken
     * @param json 数据集 "{\"touser\": \"" + 用户的openId + "\",\"msgtype\": \"text\", \"text\": {\"content\": \"" + 内容 + "\"}}";
     */
    public void sendPostText(String accessToken, String json) {
        restTemplate.postForEntity(Constans.PUBLISH_MSG_URL.replace("ACCESS_TOKEN", accessToken), json, String.class);
    }

    /**
     * 获取用户信息
     * @param openId 用户的openID
     * @param accessToken
     * @return com.xupx.wxutils.pojo.WxUserInfo 用户的信息，昵称:nickname，用户头像地址照片：headimgurl
     */
    public WxUserInfo getUserInfo(String openId, String accessToken) {
        ResponseEntity<WxUserInfo> responseEntity = restTemplate.getForEntity(Constans.USERINFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId), WxUserInfo.class);
        return responseEntity.getBody();
    }

    /**
     * 获取accessToken
     * @return com.xupx.wxutils.pojo.WxAccessToken
     */
    public WxAccessToken getAccessToken() {
        ResponseEntity<WxAccessToken> responseEntity = restTemplate.getForEntity(Constans.TOKEN_URL, WxAccessToken.class);
        return responseEntity.getBody();
    }

    /**
     * 获取用户的openId
     * @param code
     * @return com.xupx.wxutils.pojo.WxOpenId
     */
    public WxOpenId getOpenId(String code) {
        ResponseEntity<WxOpenId> responseEntity = restTemplate.getForEntity(Constans.OPEN_ID_URL.replace("CODE", code), WxOpenId.class);
        return responseEntity.getBody();
    }

    /**
     * 获取ticket
     * @param acessToken
     * @return com.xupx.wxutils.pojo.WxTicket
     */
    public WxTicket getTicket(String acessToken) {
        ResponseEntity<WxTicket> responseEntity = restTemplate.getForEntity(Constans.TICKET_URL.replace("ACCESS_TOKEN", acessToken), WxTicket.class);
        return responseEntity.getBody();
    }

    /**
     * 获取授权用户的基本信息
     * @param acessToken
     * @return com.xupx.wxutils.pojo.WxTicket
     */
    public WxUserInfo getAuthorizationUser(String acessToken,String openId) {
        ResponseEntity<WxUserInfo> responseEntity = restTemplate.getForEntity(Constans.AUTHORIZATION_USERINFO_URL.replace("ACCESS_TOKEN", acessToken).replace("OPEN_ID",openId), WxUserInfo.class);
        return responseEntity.getBody();
    }
}
